import { getQuery } from 'h3';
import { AccessModel } from '~/server/models/access.model';

// 获取访问日志列表，支持分页、关键词搜索
export default defineEventHandler(async (event): Promise<any> => {
	try {
		const query = getQuery(event);
		const keyword = query.keyword ? String(query.keyword) : '';
		const page = Number(query.page) > 0 ? Number(query.page) : 1;
		const pageSize = Number(query.pageSize) > 0 ? Number(query.pageSize) : 10;

		const filter: any = {};
		if (keyword) {
			filter.$or = [
				{ path: { $regex: keyword, $options: 'i' } },
				{ ip: { $regex: keyword, $options: 'i' } },
				{ userAgent: { $regex: keyword, $options: 'i' } },
				{ url: { $regex: keyword, $options: 'i' } },
				{ method: { $regex: keyword, $options: 'i' } },
				{ date: { $regex: keyword, $options: 'i' } },
			];
		}

		const total = await AccessModel.countDocuments(filter);
		const list = await AccessModel.find(filter)
			.sort({ createdAt: -1 })
			.skip((page - 1) * pageSize)
			.limit(pageSize)
			.lean();

		return { code: 1, message: '获取成功', data: { list, total } };
	} catch (error: any) {
		return { code: 0, message: error.message };
	}
});
